//
//  WBWBUserAccessViewModel.swift
//  XLWibo-Swift
//
//  Created by 王林 on 2016/11/16.
//  Copyright © 2016年 木木. All rights reserved.
//

import UIKit

class WBUserAccessViewModel: NSObject {
    
    //需要一个模型,用来处理数据
    var userAccount: WBUserAccount?
    
    //获取用户登录的头像
    var headUrl: URL?  {
        return URL(string: (userAccount?.avatar_large)!)
    }
    
    //判断用户是否登录
    var userLogin: Bool{
        //token != nil  && 时间 不过期
        if userAccount?.access_token != nil && isExpires == false {
            return true
        }
        return false
    }
    
    var isExpires :Bool{
        if userAccount?.espires_date?.compare(Date())  == ComparisonResult.orderedDescending{
            return false
        }
        return true
    }
    
    //重写构造函数,
    override init() {
        super.init()
        //MARK:
        // MARK: - 这里赋值是为了二次进入,不需要再次登录账号
        
        userAccount = self.getUserInfoAccount()
    }
    
    
    
    
    //单利对象
    static let shared : WBUserAccessViewModel = WBUserAccessViewModel()
    
    //获取用户token

//MARK:
// MARK: - 获取token
  func getAccessToken(code:String,finished:@escaping (Bool)->()){
    let url = "https://api.weibo.com/oauth2/access_token"
    
    let parameter = ["client_id": client_id ,
                     "client_secret": client_secret,
                     "grant_type": "authorization_code",
                     "code": code,
                     "redirect_uri":redirect_uri]
    HMNetworkTools.shared.request(method: .POST, urlString: url, parameters: parameter) { (response, error) in
        if error != nil{
//            SVProgressHUD.showError(withStatus: "网络请求失败")
           finished(false)
            return
        }
        
        self.getUserInfo(dict: response as! [String : Any],loadUserInfoFinshed:finished)
        
    }
    
}



//MARK:
// MARK: - 通过获取的token 来获取用户信息

private func getUserInfo(dict:[String:Any],loadUserInfoFinshed:@escaping (Bool)->()){
    let urlString = "https:api.weibo.com/2/users/show.json"
    let token = dict["access_token"]!
    let uid = dict["uid"]!
    
    let parameters = ["access_token" : token,
                      "uid" : uid]
//    print(parameters)
    
    HMNetworkTools.shared.request(method: .GET, urlString: urlString, parameters: parameters) { (responseObject, error) in
        if error != nil {
   loadUserInfoFinshed(false)
//            SVProgressHUD.showError(withStatus: "世界上最遥远的距离就是没有网络")
            return
        }
        
        
        //将得到的token 和 uesrInfo  两个字典合并,然后再存储
        var userInfo = responseObject as! [String:Any]
        
        for(key,value) in dict  {
            userInfo[key] = value
        }
        
        //为模型赋值
        let userInfoAccount = WBUserAccount(dict:userInfo)
        //MARK:
        // MARK: - 这里赋值,是为了第一次登录,没有数据 二奔溃
        self.userAccount = userInfoAccount
        //存档
        self.saveUserInfo(userInfoAccount: userInfoAccount)
        loadUserInfoFinshed(true)
    }
}

//存入
func saveUserInfo(userInfoAccount:WBUserAccount){
    
    NSKeyedArchiver.archiveRootObject(userInfoAccount, toFile: path)
//    print(path)
}

//取出
func getUserInfoAccount()->WBUserAccount?{
    let account = NSKeyedUnarchiver.unarchiveObject(withFile: path)
    if let userAccount = account as?WBUserAccount {
        return userAccount
    }
    
    return nil


    }



}
